<?php

namespace SC\Venus\Support\Util;
use Illuminate\Support\Str;

class Tagging
{
    protected $relation;

    /**
     * example:
     *  new Tagging('\App\Tag', this)
     */
    function __construct($model, $owner) {
        $this->model = $model;
        $this->owner = $owner;

        $pathSeg = explode('\\', $model);
        $modelName = $pathSeg[count($pathSeg)-1];
        $this->relation = Str::plural(Str::snake($modelName));
    }

    function getIds()
    {
        return $this->owner->{$this->relation}->pluck('id');
    }

    function setIds($Ids)
    {
        $refIds = $this->owner->{$this->relation}->pluck('id')->all();;

        //delete
        foreach($refIds as $refId) {
            if (!\in_array($refId, $Ids)) {
                $this->owner->{$this->relation}()->detach($refId);
            }
        }

        //insert
        foreach($Ids as $id) {
            if (!\in_array($id, $refIds)) {
                $this->owner->{$this->relation}()->attach($id);
            }
        }
    }

    function getNames()
    {
        return $this->owner->{$this->relation}->pluck('name');
    }

    function setNames($names)
    {
        $refs = $this->owner->{$this->relation};
        $refsName = $refs->pluck('name')->all();

        //delete
        foreach($refs as $ref) {
            if (!\in_array($ref->name, $names)) {
                $this->owner->{$this->relation}()->detach($ref->id);
            }
        }

        //insert
        foreach($names as $name) {
            if (!\in_array($name, $refsName)) {
                //$newTag = \App\Tag::firstOrCreate(['name' => $newName]);
                //$this->tags()->attach($newTag);

                $newRef = $this->model::firstOrCreate(['name' => $name]);
                $this->owner->{$this->relation}()->attach($newRef);
            }
        }
    }
}